<template>
  <el-dialog @close="tjwkpzCancel('tjwkpzRuleForm')" :close-on-click-modal="false" title="提交尾款凭证"
    :visible.sync="tjwkpzVisible" width="900px">
    <div class="scroll-view">
      <el-form :model="tjwkpzRuleForm" :rules="tjwkpzRules" ref="tjwkpzRuleForm" label-position="left" inline>
        <el-form-item label="实付尾款金额" prop="amount_collected">
          <el-input @input="settlementDiscountAmountFunc" class="input-box" v-model="tjwkpzRuleForm.amount_collected"
            clearable v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="结算优惠金额" prop="settlement_discount_amount">
          <el-input @input="settlementDiscountAmountFunc" class="input-box"
            v-model="tjwkpzRuleForm.settlement_discount_amount" clearable v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="待付款金额" prop="unpaid_amount">
          <el-input disabled class="input-box" v-model="tjwkpzRuleForm.unpaid_amount" clearable
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="最终结算总额" prop="final_settlement_amount">
          <el-input disabled class="input-box" clearable v-model="tjwkpzRuleForm.final_settlement_amount"
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="最终利润金额" prop="final_profit_amount">
          <el-input disabled class="input-box" v-model="tjwkpzRuleForm.final_profit_amount" clearable
            v-input-limit="2"></el-input>
        </el-form-item>
        <el-form-item label="收款账户" prop="receiving_account_id">
          <el-select filterable class="input-box" clearable v-model="tjwkpzRuleForm.receiving_account_id" placeholder="请选择">
            <el-option v-for="item in companyList" :key="item.id" :label="item.account_name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算完成日期" prop="settlement_completion_date">
          <el-date-picker class="input-box" v-model="tjwkpzRuleForm.settlement_completion_date" type="date"
            :picker-options="pickerOptionsEnd" placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="质保截止日期" prop="warranty_deadline_date">
          <el-date-picker class="input-box" v-model="tjwkpzRuleForm.warranty_deadline_date" type="date"
            :picker-options="pickerOptionsEnd" placeholder="选择日期" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="支付凭证 (.jpg,.png,.gif)" prop="payment_voucher">
          <el-input style="position: absolute; z-index: 0; top: -999999px"
            v-model="tjwkpzRuleForm.payment_voucher.length"></el-input>
          <el-upload accept="image/*" :on-change="(file, fileList) => {
            tjwkpzChangeFile(file, fileList, 'payment_voucher');
          }
            " :on-remove="(file, fileList) => {
              tjwkpzFileRemove(file, fileList, 'payment_voucher');
            }
              " :auto-upload="false" :file-list="tjwkpzRuleForm.payment_voucher" action="#"><el-button size="small"
              icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :rows="4" class="input-box" v-model="tjwkpzRuleForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer">
      <div class="flex ac jb">
        <span class="tips" v-if="!showTip"></span>
        <el-button v-if="showTip" class="tips" type="text">已超出优惠权限，需客户总监审批</el-button>
        <span>
          <el-button type="primary" @click="tjwkpzSubmit('tjwkpzRuleForm')" :disabled="diaLoading"
            :loading="diaLoading">提交</el-button>
            <el-button @click="tjwkpzCancel('tjwkpzRuleForm')">关闭</el-button>
        </span>
      </div>
    </span>
  </el-dialog>
</template>
<script>
import projectApi from "@/api/projectApi";
import companyApi from "@/api/companyApi";
import adminApi from "@/api/adminApi";
import { getUserInfo } from "@/utils/auth";
import foremanApi from "@/api/foremanApi";
import * as math from "mathjs";

export default {
  name: "",
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false,
      required: false,
    },
    project_id: {
      required: false,
    },
    detailData: {
      required: false,
    },
    jsdData: {
      required: false,
    },
    signing_company_data: {
      required: false,
    }
  },
  data() {
    var payment_voucher = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传支付凭证"));
      } else {
        callback();
      }
    };
    return {
      pickerOptionsEnd: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      tjwkpzRuleForm: {
        remark: "",
        amount_collected: "",
        settlement_discount_amount: "",
        final_settlement_amount: "",
        unpaid_amount: "",
        final_profit_amount: "",
        receiving_account_id: "",
        settlement_completion_date: "",
        warranty_deadline_date: "",
        payment_voucher: [],
      },
      tjwkpzVisible: false,
      tjwkpzRules: {
        amount_collected: [
          { required: true, message: "请输入实付尾款金额", trigger: "change" },
        ],
        settlement_discount_amount: [
          { required: true, message: "请输入结算优惠金额", trigger: "change" },
        ],

        final_settlement_amount: [
          { required: true, message: "请输入最终结算总额", trigger: "change" },
        ],
        unpaid_amount: [
          { required: true, message: "请输入待付款金额", trigger: "change" },
        ],
        final_profit_amount: [
          { required: true, message: "请输入最终利润金额", trigger: "change" },
        ],
        receiving_account_id: [
          { required: true, message: "请选择收款账户", trigger: "change" },
        ],
        settlement_completion_date: [
          { required: true, message: "请选择结算完成日期", trigger: "change" },
        ],
        warranty_deadline_date: [
          { required: true, message: "请选择质保截止日期", trigger: "change" },
        ],
        payment_voucher: {
          required: true,
          validator: payment_voucher,
          trigger: "change",
        },
      },
      diaLoading: false,
      companyList: [],
      showTip: false,
    };
  },
  watch: {
    addDialogVisible(val1, val2) {
      if (this.addDialogVisible) {
        this.getCompanyList(1);
        let tjwkpzRuleForm = this.tjwkpzRuleForm;
        let detailData = this.detailData;
        let jsdData = this.jsdData;
        let userInfoData = getUserInfo();
        console.log(detailData, "1111111111111111", userInfoData.settlement_discount_ratio, this.signing_company_data);
        let unpaid_amount = 0;//待付款金额
        let final_settlement_amount = 0;//最终结算总额
        let final_profit_amount = 0;//最终利润
        // 待付款金额
        unpaid_amount = math.format(
          math.subtract(
            math.bignumber(jsdData.settlement_amount),
            math.bignumber(jsdData.paid_amount),
          )
        );
        unpaid_amount = ((unpaid_amount * 100) / 100).toFixed(2);
        tjwkpzRuleForm.unpaid_amount = unpaid_amount;
        console.log(unpaid_amount, "待付款金额（初步计算）")
        // 最终结算总额
        final_settlement_amount = jsdData.settlement_amount;
        console.log(final_settlement_amount, "最终结算总额（初步计算）")
        tjwkpzRuleForm.final_settlement_amount = final_settlement_amount;
        // 最终利润
        final_profit_amount = math.format(
          math.subtract(
            math.bignumber(final_settlement_amount),
            math.bignumber(jsdData.settlement_cost_amount),
          )
        );
        final_profit_amount = ((final_profit_amount * 100) / 100).toFixed(2);
        tjwkpzRuleForm.final_profit_amount = final_profit_amount;
        console.log(final_profit_amount, "最终利润（初步计算）")

        // 继承合同的签约主体
        tjwkpzRuleForm.receiving_account_id = this.signing_company_data.signing_company_id;
        this.tjwkpzRuleForm = tjwkpzRuleForm;
      }
      this.tjwkpzVisible = this.addDialogVisible;
    },
  },
  computed: {},
  mounted() { },
  methods: {
    // 结算优惠金额输入  实付尾款金额输入
    settlementDiscountAmountFunc() {
      let tjwkpzRuleForm = this.tjwkpzRuleForm;
      let detailData = this.detailData;
      let jsdData = this.jsdData;
      let userInfoData = getUserInfo();
      console.log(userInfoData, '用户信息')
      let amount_collected = tjwkpzRuleForm.amount_collected || 0;//实付尾款金额
      let settlement_discount_amount = tjwkpzRuleForm.settlement_discount_amount || 0;//结算优惠金额
      let unpaid_amount = tjwkpzRuleForm.unpaid_amount || 0;//待付款金额
      let final_settlement_amount = tjwkpzRuleForm.final_settlement_amount || 0;//最终结算总额
      let final_profit_amount = tjwkpzRuleForm.final_profit_amount || 0;//最终利润

      // 待付款金额
      let unpaid_amountVal = math.format(
        math.add(
          math.bignumber(amount_collected),
          math.bignumber(settlement_discount_amount),
          math.bignumber(jsdData.paid_amount)
        )
      );
      unpaid_amount = math.format(
        math.subtract(
          math.bignumber(jsdData.settlement_amount),
          math.bignumber(unpaid_amountVal),
        )
      );
      unpaid_amount = ((unpaid_amount * 100) / 100).toFixed(2);
      tjwkpzRuleForm.unpaid_amount = unpaid_amount;
      console.log(unpaid_amount, "待付款金额")
      // 最终结算总额
      final_settlement_amount = math.format(
        math.subtract(
          math.bignumber(jsdData.settlement_amount),
          math.bignumber(settlement_discount_amount),
        )
      );
      final_settlement_amount = ((final_settlement_amount * 100) / 100).toFixed(2);
      tjwkpzRuleForm.final_settlement_amount = final_settlement_amount;
      console.log(final_settlement_amount, "最终结算总额")

      // 最终利润
      final_profit_amount = math.format(
        math.subtract(
          math.bignumber(final_settlement_amount),
          math.bignumber(jsdData.settlement_cost_amount),
        )
      );
      final_profit_amount = ((final_profit_amount * 100) / 100).toFixed(2);
      tjwkpzRuleForm.final_profit_amount = final_profit_amount;
      console.log(final_profit_amount, "最终利润", jsdData.settlement_cost_amount)

      // 是否超出优惠权限
      if (Number(settlement_discount_amount) > Number(userInfoData.settlement_discount_ratio)) {
        this.showTip = true;
      } else {
        this.showTip = false;
      }



      this.tjwkpzRuleForm = tjwkpzRuleForm;
    },
    // 收款账户列表
    getCompanyList(account_type) {
      companyApi
        .getCompanyList({
          page: 1,
          num: 9999,
          keyword: "",
          account_type,
        })
        .then((res) => {
          console.log(res, account_type == 1 ? "公司列表" : "收款账户");
          if (res.code == 200) {
            this.companyList = res.data.list;
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((err) => {
          this.$message.warning(err.message);
        });
    },
    tjwkpzCancel(formName) {
      this.tjwkpzRuleForm = {
        remark: "",
        amount_collected: "",
        settlement_discount_amount: "",
        final_settlement_amount: "",
        unpaid_amount: "",
        final_profit_amount: "",
        receiving_account_id: "",
        settlement_completion_date: "",
        warranty_deadline_date: "",
        payment_voucher: [],
      };
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
        this.$emit("onClose", true);
      });
    },
    tjwkpzSubmit(formName) {
      let tjwkpzRuleForm = this.tjwkpzRuleForm;
      let companyList = this.companyList;
      let receiving_account_name = '';
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let index = companyList.findIndex(item => {
            return item.id == tjwkpzRuleForm.receiving_account_id
          })
          receiving_account_name = companyList[index].account_name;
          let formdata = new FormData();
          formdata.append(
            "data",
            JSON.stringify({
              project_id: this.project_id,
              amount_collected: tjwkpzRuleForm.amount_collected,
              settlement_discount_amount:
                tjwkpzRuleForm.settlement_discount_amount,
              final_settlement_amount: tjwkpzRuleForm.final_settlement_amount,
              unpaid_amount: tjwkpzRuleForm.unpaid_amount,
              final_profit_amount: tjwkpzRuleForm.final_profit_amount,
              receiving_account_id: tjwkpzRuleForm.receiving_account_id,
              receiving_account_name,
              settlement_completion_date:
                tjwkpzRuleForm.settlement_completion_date,
              warranty_deadline_date: tjwkpzRuleForm.warranty_deadline_date,
              remark: tjwkpzRuleForm.remark,
            })
          );
          tjwkpzRuleForm.payment_voucher.forEach((item) => {
            formdata.append("payment_voucher[]", item.raw);
          });
          this.diaLoading = true;
          projectApi
            .finalPaymentCollection(formdata)
            .then((res) => {
              console.log(res, "提交尾款凭证");
              this.diaLoading = false;
              if (res.code == 200) {
                this.$emit("onSuccess", true);
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    tjwkpzChangeFile(file, list, type) {
      let tjwkpzRuleForm = this.tjwkpzRuleForm;
      tjwkpzRuleForm[type] = [file];
      this.tjwkpzRuleForm;
    },
    tjwkpzFileRemove(file, list, type) {
      let tjwkpzRuleForm = this.tjwkpzRuleForm;
      tjwkpzRuleForm[type] = list;
      this.tjwkpzRuleForm;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>